package com.campusexpresspickup.controller;

import com.campusexpresspickup.entity.UserMenu;
import com.campusexpresspickup.service.IUserMenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.campusexpresspickup.common.RestResponse;
import com.campusexpresspickup.dto.UserMenuNode;
import com.campusexpresspickup.page.UserMenuPage;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 后台菜单表 前端控制器
 * </p>
 *
 * @author lq
 * @since 2021-11-17
 */
@RestController
@RequestMapping("/user-menu")
public class UserMenuController {

  private final IUserMenuService userMenuService;

  public UserMenuController(IUserMenuService userMenuService) {
    this.userMenuService = userMenuService;
  }

  @PostMapping(value = "/create", name = "添加菜单")
  public Object create(@RequestBody UserMenu userMenu) {
    int count;
    userMenu.setCreateTime(LocalDateTime.now());
    if (userMenu.getId() != null) {
      count = userMenuService.getBaseMapper().updateById(userMenu);
    } else {
      count = userMenuService.getBaseMapper().insert(userMenu);
    }
    if (count > 0) {
      return RestResponse.ok("创建成功");
    }
    return RestResponse.error("创建失败");
  }

  @PostMapping(value = "/list", name = "列表")
  public Object getMenuList(@RequestBody UserMenuPage userMenuPage) {
    PageHelper.startPage(userMenuPage.getPageStart(), userMenuPage.getPageSize());
    List<UserMenu> userMenuList = userMenuService.getUserResourceList(userMenuPage);
    return RestResponse.ok(new PageInfo<>(userMenuList), "查询成功");
  }

  @GetMapping(value = "/{id}", name = "详情")
  public Object getMenuById(@PathVariable Integer id) {
    return RestResponse.ok(userMenuService.getBaseMapper().selectById(id), "查询成功");
  }

  @GetMapping(value = "/menuTree", name = "菜单层级")
  public Object menuTree() {
    List<UserMenuNode> userMenuNodes = userMenuService.treeList();
    return RestResponse.ok(userMenuNodes, "查询成功");
  }

  @GetMapping(value = "/delete/{id}", name = "删除")
  public Object deleteMenuById(@PathVariable Integer id) {
    int delCount = userMenuService.getBaseMapper().deleteById(id);
    if (delCount > 0) {
      RestResponse.ok("删除成功");
    }
    return RestResponse.error("删除失败");
  }
}
